$(function () {
    if ($('#userType').prop('checked')) {
        $('div[data-userType]').hide().next('div.hr-line-dashed').hide();
    }
    $('body').on('click', '#saveAndContinue', function () { //保存继续
        verifyAccount(true);
    }).on('click', '#saveAndReturn', function () { //保存返回
        verifyAccount(false);
    }).on('click', '#saveCancel', function () { //取消
        window.location = baseloaction + '/admin/manage/user/querySysUserList';
    }).on('click', 'label[for=userType]', function () { //用户类型切换
        if ($('#userType').prop('disabled')) return false;
        if ($('#' + $(this).attr('for')).prop('checked')) {
            $('div[data-' + $(this).attr('for') + ']').show().next().show();
            $('input[name=isExp]').val('OFF');
            $('#checkOn').addClass("hide");
            $('#checkOff').removeClass("hide");
            $("input[name='userType']").val(1);
        } else {
            $('div[data-' + $(this).attr('for') + ']').hide().next().hide();
            $('input[name=isExp]').val('ON');
            $('#checkOn').removeClass("hide");
            $('#checkOff').addClass("hide");
            $("input[name='userType']").val(2);
        }
    }).on('click', '#group', function () { //部门选择
        getGroupWin();
    }).on('click', 'label[for=sync]', function () {
        if ($('#sync').prop('disabled')) return false;
        if ($('#' + $(this).attr('for')).prop('checked')) {
            $('div[data-' + $(this).attr('for') + ']').show().next().show();
            $('input[name=isSync]').val('OFF');
            $('#isSyncOn').addClass("hide");
            $('#isSyncOff').removeClass("hide");
        } else {
            $('div[data-' + $(this).attr('for') + ']').hide().next().hide();
            $('input[name=isSync]').val('ON');
            $('#isSyncOn').removeClass("hide");
            $('#isSyncOff').addClass("hide");
        }
    }).on("click","#remove-image",function () {//删除头像
        removePageImg();
    }).on("click","#sysUserImage",function () {//点击图片上传按钮
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadCallback',
            cut:true,//开启剪切
            imgSize:DEFAULT_SYS_USER_IMG_SIZE,//剪切上传后生成图片的规格（开启剪切才起使用）
            aspectRatio:1/1//剪切区域的高宽比例（开启剪切才起使用）
        });
    }).on("click","#newRole",function(){
        newRole();

    });

    /**
     * 保存系统用户
     * @param isContinue true 保存继续创建 false 保存返回
     */
    function saveSysUser(isContinue) {

        var params = $('#saveSysUser').serialize();
        $.ajax({
            url: baseloaction + "/admin/manage/user/saveSysUser",
            data: params,
            type:'post',
            dataType: 'json',
            success: function (response) {
                icModale(0, response.message);
                if (response.success) {
                    if (isContinue) {
                        window.location.href = baseloaction + '/admin/manage/user/initAdd';
                    } else {
                        setTimeout(function () {
                            window.location = baseloaction + '/admin/manage/user/querySysUserList';
                        }, 2500);
                    }
                }
            }
        });
    }
    function verifyAccount(isContinue){
        if($("#sync").val()=="on"){
            $.ajax({
                url: baseloaction + "/admin/user/cus/verifyAccount",
                data: {account:$("input[name='account']").val()},
                type:'post',
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        if(response.entity){
                            saveSysUser(isContinue);
                        }else{
                            icModale(0,"无法将该账号同步到前台，前台已存在");
                        }
                    }
                },
                error:function (error) {
                    icModale(0,"验证账号是否可用于前台失败");
            }
            });

        }else{
            saveSysUser(isContinue);
        }
    }
});

/**
 * 选择部门回调
 * @param obj
 */
function groupCallback(obj) {
    $('#hiddenGroupId').val(obj.groupId);
    $('#hiddenGroupIds').val(',' + obj.groupIds + ',');
    $('#group').val(obj.groupName);
}

//上传回调
function uploadCallback(result) {
    if(result!=null){
        $("input[name='userImg']").val(encodeURIComponent(JSON.stringify(result)));
        $("#material-image").attr("src",result.pcUrlMap.large);
        $("#file-names").text(result.fileName);
        $("#create-time").text(result.createTime);
    }
}

/**
 * 新建角色
 */
function newRole (){
    parent.layer.open({
        type: 2,
        area: winArea,
        btn: ['确定','取消'],
        content:baseloaction+'/admin/manage/role/initAddRole?type=1',
        skin: 'layui-layer-demo',
        title: '<strong>新建角色</strong>',
        end:function(){
            setRoleOpOption();
        }
    });
}

/**
 * 新建角色
 */
function setRoleOpOption (){
    if(sessionStorage.newRoleName!=undefined&&sessionStorage.newRoleId!=undefined){
        $('select[name="roleIds"]').get(0).add(new Option(sessionStorage.newRoleName, sessionStorage.newRoleId, true, true));
        $('select[name="roleIds"]').trigger("chosen:updated");
        $('select[name="roleIds"]').chosen();
        sessionStorage.removeItem("newRoleId");
        sessionStorage.removeItem("newRoleName");
    }
}
